<template>
  <div class="page-container">
    <button class="back-button" @click="goToHome">
      <span class="icon-arrow-left"></span>
      返回首页
    </button>
    
    <div class="page-header">
      <h1>值班安排</h1>
      <p>安排和管理团队成员的值班计划，确保工作无缝衔接</p>
    </div>

    <div class="controls-bar">
      <div class="date-nav">
        <button class="icon-btn" @click="prevMonth"><i class="icon-chevron-left"></i></button>
        <h2>{{ currentMonth }}</h2>
        <button class="icon-btn" @click="nextMonth"><i class="icon-chevron-right"></i></button>
      </div>
      
      <div class="view-controls">
        <button class="view-btn" :class="{ active: viewMode === 'month' }" @click="viewMode = 'month'">月视图</button>
        <button class="view-btn" :class="{ active: viewMode === 'week' }" @click="viewMode = 'week'">周视图</button>
        <button class="primary-btn" @click="showAddDutyModal = true">
          <i class="icon-plus"></i> 添加值班
        </button>
      </div>
    </div>

    <!-- 月视图 -->
    <div class="calendar-month" v-if="viewMode === 'month'">
      <div class="weekdays">
        <div class="weekday">周日</div>
        <div class="weekday">周一</div>
        <div class="weekday">周二</div>
        <div class="weekday">周三</div>
        <div class="weekday">周四</div>
        <div class="weekday">周五</div>
        <div class="weekday">周六</div>
      </div>
      
      <div class="calendar-days">
        <div class="calendar-day empty" v-for="(empty, index) in leadingEmptyDays" :key="'empty-' + index"></div>
        
        <div class="calendar-day" 
             v-for="day in currentMonthDays" 
             :key="day.date"
             :class="{ today: day.isToday, past: day.isPast }">
          <div class="day-number">{{ day.day }}</div>
          
          <div class="duty-items">
            <div class="duty-item" 
                 v-for="duty in getDutiesForDay(day.date)" 
                 :key="duty.id"
                 :style="{ backgroundColor: getTeamColor(duty.teamId) }"
                 @click="editDuty(duty)">
              <div class="duty-team">{{ getTeamName(duty.teamId) }}</div>
              <div class="duty-person">{{ duty.person }}</div>
            </div>
          </div>
          
          <button class="add-duty-btn" @click="addDutyForDate(day.date)">
            <i class="icon-plus"></i>
          </button>
        </div>
        
        <div class="calendar-day empty" v-for="(empty, index) in trailingEmptyDays" :key="'empty-end-' + index"></div>
      </div>
    </div>

    <!-- 周视图 -->
    <div class="calendar-week" v-if="viewMode === 'week'">
      <div class="time-column">
        <div class="time-slot" v-for="hour in 24" :key="hour">
          {{ hour }}:00
        </div>
      </div>
      
      <div class="day-column" v-for="day in currentWeekDays" :key="day.date">
        <div class="day-header" :class="{ today: day.isToday }">
          <div class="day-name">{{ getWeekDayName(day.weekDay) }}</div>
          <div class="day-date">{{ day.month }}-{{ day.day }}</div>
        </div>
        
        <div class="day-content">
          <div class="duty-block"
               v-for="duty in getDutiesForDay(day.date)"
               :key="duty.id"
               :style="{ 
                 top: `${duty.startHour * 40}px`, 
                 height: `${(duty.endHour - duty.startHour) * 40}px`,
                 backgroundColor: getTeamColor(duty.teamId)
               }"
               @click="editDuty(duty)">
            <div class="duty-team">{{ getTeamName(duty.teamId) }}</div>
            <div class="duty-person">{{ duty.person }}</div>
            <div class="duty-time">{{ duty.startHour }}:00-{{ duty.endHour }}:00</div>
          </div>
          
          <button class="add-duty-btn" @click="addDutyForDate(day.date)">
            <i class="icon-plus"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑值班弹窗 -->
    <div class="modal-backdrop" v-if="showAddDutyModal">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ isEditingDuty ? '编辑值班' : '添加值班' }}</h3>
          <button class="close-btn" @click="showAddDutyModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveDuty">
            <div class="form-group">
              <label>日期 *</label>
              <input type="date" v-model="currentDuty.date" required>
            </div>
            <div class="form-group">
              <label>所属团队 *</label>
              <select v-model="currentDuty.teamId" required>
                <option value="">请选择团队</option>
                <option v-for="team in teams" :key="team.id" :value="team.id">{{ team.name }}</option>
              </select>
            </div>
            <div class="form-group">
              <label>值班人员 *</label>
              <input type="text" v-model="currentDuty.person" placeholder="输入值班人员姓名" required>
            </div>
            <div class="form-row">
              <div class="form-group half">
                <label>开始时间 (时) *</label>
                <select v-model="currentDuty.startHour" required>
                  <option v-for="hour in 23" :key="hour" :value="hour">{{ hour }}</option>
                </select>
              </div>
              <div class="form-group half">
                <label>结束时间 (时) *</label>
                <select v-model="currentDuty.endHour" required>
                  <option v-for="hour in Array.from({length:24}, (_,i) => i+1)" :key="hour" :value="hour">{{ hour }}</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label>备注</label>
              <textarea v-model="currentDuty.notes" rows="2"></textarea>
            </div>
            <div class="modal-footer">
              <button type="button" class="secondary-btn" @click="showAddDutyModal = false">取消</button>
              <button type="submit" class="primary-btn">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DutySchedule',
  data() {
    const today = new Date();
    return {
      viewMode: 'month', // 'month' 或 'week'
      currentDate: today,
      showAddDutyModal: false,
      isEditingDuty: false,
      currentDuty: {
        id: null,
        date: '',
        teamId: '',
        person: '',
        startHour: 9,
        endHour: 18,
        notes: ''
      },
      teams: [
        { id: 1, name: '前端开发团队', color: '#3498db' },
        { id: 2, name: '后端开发团队', color: '#2ecc71' },
        { id: 3, name: '测试团队', color: '#f39c12' }
      ],
      duties: [
        {
          id: 1,
          date: this.formatDate(today),
          teamId: 1,
          person: '张三',
          startHour: 9,
          endHour: 18,
          notes: '负责前端紧急问题处理'
        },
        {
          id: 2,
          date: this.formatDate(today),
          teamId: 2,
          person: '李四',
          startHour: 9,
          endHour: 18,
          notes: '负责服务器监控'
        },
        {
          id: 3,
          date: this.formatDate(new Date(today.setDate(today.getDate() + 1))),
          teamId: 3,
          person: '王五',
          startHour: 9,
          endHour: 18,
          notes: '负责线上问题测试'
        }
      ]
    };
  },
  computed: {
    currentMonth() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth() + 1;
      return `${year}年${month}月`;
    },
    currentMonthDays() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      const daysInMonth = new Date(year, month + 1, 0).getDate();
      const today = new Date();
      
      return Array.from({ length: daysInMonth }, (_, i) => {
        const day = i + 1;
        const date = new Date(year, month, day);
        const dateStr = this.formatDate(date);
        const todayStr = this.formatDate(today);
        
        return {
          date: dateStr,
          day,
          month: month + 1,
          weekDay: date.getDay(),
          isToday: dateStr === todayStr,
          isPast: dateStr < todayStr
        };
      });
    },
    leadingEmptyDays() {
      const firstDayOfMonth = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth(),
        1
      ).getDay();
      return firstDayOfMonth;
    },
    trailingEmptyDays() {
      const lastDayOfMonth = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth() + 1,
        0
      ).getDay();
      return 6 - lastDayOfMonth;
    },
    currentWeekDays() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      const date = this.currentDate.getDate();
      const dayOfWeek = this.currentDate.getDay() || 7; // 转换为1-7 (周一-周日)
      
      // 计算本周一的日期
      const monday = new Date(year, month, date - (dayOfWeek - 1));
      
      const today = new Date();
      const todayStr = this.formatDate(today);
      
      // 生成周一到周日的日期
      return Array.from({ length: 7 }, (_, i) => {
        const current = new Date(monday);
        current.setDate(monday.getDate() + i);
        
        return {
          date: this.formatDate(current),
          day: current.getDate(),
          month: current.getMonth() + 1,
          weekDay: current.getDay(),
          isToday: this.formatDate(current) === todayStr
        };
      });
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    prevMonth() {
      this.currentDate = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth() - 1,
        1
      );
    },
    nextMonth() {
      this.currentDate = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth() + 1,
        1
      );
    },
    getDutiesForDay(date) {
      return this.duties.filter(duty => duty.date === date);
    },
    getTeamName(teamId) {
      const team = this.teams.find(t => t.id === teamId);
      return team ? team.name : '未知团队';
    },
    getTeamColor(teamId) {
      const team = this.teams.find(t => t.id === teamId);
      return team ? `${team.color}40` : '#95a5a640'; // 带透明度
    },
    getWeekDayName(weekDay) {
      const names = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return names[weekDay];
    },
    addDutyForDate(date) {
      this.isEditingDuty = false;
      this.currentDuty = {
        id: null,
        date,
        teamId: '',
        person: '',
        startHour: 9,
        endHour: 18,
        notes: ''
      };
      this.showAddDutyModal = true;
    },
    editDuty(duty) {
      this.isEditingDuty = true;
      this.currentDuty = { ...duty };
      this.showAddDutyModal = true;
    },
    saveDuty() {
      if (this.currentDuty.startHour >= this.currentDuty.endHour) {
        alert('结束时间必须晚于开始时间');
        return;
      }
      
      if (this.isEditingDuty) {
        const index = this.duties.findIndex(d => d.id === this.currentDuty.id);
        this.duties.splice(index, 1, this.currentDuty);
      } else {
        this.currentDuty.id = Date.now();
        this.duties.push(this.currentDuty);
      }
      
      this.showAddDutyModal = false;
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin: 20px 0 30px;
}

.page-header h1 {
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.controls-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.date-nav {
  display: flex;
  align-items: center;
  gap: 15px;
}

.date-nav h2 {
  margin: 0;
  color: #2c3e50;
}

.view-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.view-btn {
  background: #f8f9fa;
  border: 1px solid #ddd;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.view-btn.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

/* 月视图样式 */
.calendar-month {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.weekday {
  padding: 12px;
  text-align: center;
  font-weight: 500;
  color: #7f8c8d;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-gap: 1px;
  background: #eee;
}

.calendar-day {
  min-height: 120px;
  background: white;
  padding: 8px;
  position: relative;
}

.calendar-day.empty {
  background: #f9f9f9;
}

.calendar-day.today {
  background: #f0f7ff;
}

.calendar-day.past {
  opacity: 0.7;
}

.day-number {
  font-weight: 500;
  margin-bottom: 8px;
  color: #2c3e50;
}

.duty-items {
  margin-bottom: 8px;
  max-height: 80px;
  overflow-y: auto;
}

.duty-item {
  padding: 4px 6px;
  border-radius: 4px;
  margin-bottom: 4px;
  font-size: 12px;
  color: #2c3e50;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.duty-team {
  font-weight: 500;
}

.duty-person {
  font-size: 11px;
}

.add-duty-btn {
  position: absolute;
  bottom: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #f1f2f6;
  border: none;
  color: #7f8c8d;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: all 0.2s;
}

.add-duty-btn:hover {
  background: #3498db;
  color: white;
}

/* 周视图样式 */
.calendar-week {
  display: grid;
  grid-template-columns: 80px 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  grid-gap: 1px;
  background: #eee;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.time-column {
  background: #f8f9fa;
}

.time-slot {
  height: 40px;
  padding: 8px;
  font-size: 12px;
  color: #7f8c8d;
  border-bottom: 1px solid #eee;
}

.day-column {
  min-width: 180px;
}

.day-header {
  background: #f8f9fa;
  padding: 10px;
  text-align: center;
  border-bottom: 1px solid #eee;
  font-weight: 500;
}

.day-header.today {
  background: #ebf5fb;
  color: #3498db;
}

.day-name {
  font-size: 14px;
  margin-bottom: 4px;
}

.day-date {
  font-size: 12px;
  opacity: 0.8;
}

.day-content {
  height: calc(960px - 56px); /* 24小时 * 40px - 头部高度 */
  background: white;
  position: relative;
  overflow: hidden;
}

.duty-block {
  position: absolute;
  left: 4px;
  right: 4px;
  border-radius: 4px;
  padding: 4px;
  font-size: 12px;
  color: #2c3e50;
  cursor: pointer;
  overflow: hidden;
  box-sizing: border-box;
}

.duty-time {
  font-size: 11px;
  opacity: 0.8;
}

/* 按钮样式 */
.primary-btn {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
}

.primary-btn:hover {
  background: #2980b9;
  transform: translateY(-1px);
}

.secondary-btn {
  background: #ecf0f1;
  color: #2c3e50;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.secondary-btn:hover {
  background: #dcdde1;
}

.icon-btn {
  background: none;
  border: none;
  color: #7f8c8d;
  cursor: pointer;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.icon-btn:hover {
  background: #f1f1f1;
  color: #3498db;
}

/* 弹窗样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-row {
  display: flex;
  gap: 10px;
}

.half {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #7f8c8d;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

/* 图标样式模拟 */
.icon-plus::before { content: "+"; }
.icon-chevron-left::before { content: "◀"; }
.icon-chevron-right::before { content: "▶"; }
.icon-arrow-left::before { content: "←"; }
</style>